package com.hnu.java.test.tracfic;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class Road {

	private List<String> cars = new ArrayList<String>();
	
	private String name;
	@SuppressWarnings("unused")
	private Lamp lamp;
	 Road(String name){
		this.name = name;
		
		ExecutorService pool= Executors.newSingleThreadExecutor();
		pool.execute(new Runnable() {
			
			public void run() {
				for(int i=0;i<100;i++){
					cars.add(Road.this.name + "_" +i);
					try {
						Thread.sleep((new Random().nextInt(10)+1)*1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}
		});
		
		
		  ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
		    timer.scheduleAtFixedRate(new Runnable() {
				
				public void run() {
					if(cars.size()>0){
						boolean isLighted = Lamp.valueOf(Road.this.name).isLight();
						if(isLighted){
							cars.remove(0);
							System.out.println(Road.this.name+":"+cars.remove(0)+" is tracficing");
						}
					}
					
				}
			},
		    		1,
		    		1,
		    		TimeUnit.SECONDS);
			
	}
	

}
